package main

import (
	"crypto/md5"
	"fmt"
	"html/template"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

func parseHtml(fileName string) *template.Template {
	t, err := template.ParseFiles(dir + "/" + fileName + ".html")
	if err != nil {
		log.Printf("access %s err, err = %s", fileName, err.Error())
		return nil
	}
	return t
}

func handle(w http.ResponseWriter, r *http.Request, fileName string, data interface{}) {
	log.Printf("access %s ip = %s\n", fileName, r.RemoteAddr)
	t := parseHtml(fileName)
	if t != nil {
		_ = t.Execute(w, data)
		return
	}
	_, _ = fmt.Fprintf(w, "err")
}

func Sort(arr []No) {
	if len(arr) > 0 {
		QuickSort(arr, 0, len(arr)-1)
		Reverse(arr)
	}
}

//数组倒序函数
func Reverse(arr []No) {
	length := len(arr)
	for i := 0; i < length/2; i++ {
		temp := arr[length-1-i]
		arr[length-1-i] = arr[i]
		arr[i] = temp
	}
}

/**
  快排
*/
func QuickSort(nums []No, start, end int) {
	if start >= end {
		return
	}
	mid := Partition(nums, start, end)
	QuickSort(nums, start, mid)
	QuickSort(nums, mid+1, end)
}

func Partition(nums []No, start, end int) int {
	temp := nums[start]
	low := start
	height := end
	for low < height {
		for low < height && temp.GetNo() < nums[height].GetNo() {
			height--
		}
		if low < height {
			nums[low] = nums[height]
		}
		for low < height && temp.GetNo() > nums[low].GetNo() {
			low++
		}
		if low < height {
			nums[height] = nums[low]
		}
	}
	nums[low] = temp
	return low
}

/**
  限制ip的评论和留言间隔时间 防机器人
*/
var AccessMap = make(map[string]time.Time)

func checkAccess(r *http.Request) bool {
	log.Println("access remark or message ip = " + r.RemoteAddr)
	ip := strings.Split(r.RemoteAddr, ":")[0]
	ipAddr := net.ParseIP(ip)
	if ipAddr == nil {
		return false
	}
	t, ok := AccessMap[ip]
	if !ok {
		AccessMap[ip] = time.Now()
		return true
	}
	now := time.Now()
	sub := now.Sub(t)
	if sub.Minutes() < 2 {
		return false
	}
	AccessMap[ip] = now
	return true
}

// 判断文件夹是否存在
func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

func md5V2(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	md5str := fmt.Sprintf("%x", has)
	return md5str
}

/**
  十分钟清理一次
*/
func deleteAccess() {
	for {
		time.Sleep(10 * time.Minute)
		for k, v := range AccessMap {
			sub := time.Now().Sub(v)
			if sub.Minutes() >= 2 {
				delete(AccessMap, k)
			}
		}
	}
}

func PanicIfErrMsg(err error, msg string) {
	if err != nil {
		panic(msg)
	}
}
